<?php

namespace magein\laravel\seecms\command;

use Illuminate\Console\Command;
use magein\seecms\library\Backup;

class Database extends Command
{
    /**
     * 命令名称及签名
     *
     * @var string
     */
    protected $signature = 'seecms:database {action?} {--m|mail=} {--t|tables=}';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = 'seecms database';

    protected $help = '
Usage:
    php artisan seecms:database  run               执行migrate命令
    php artisan seecms:database  seed              执行初始化命令
    php artisan seecms:database  backup            执行备份
    php artisan seecms:database  backup --mail     将备份结果以邮件的形式发送到配置的邮箱
    php artisan seecms:database  backup -m         同上
';

    public function handle()
    {
        $action = $this->argument('action');
        $mail = $this->option('mail');
        $tables = $this->option('tables');

        if (in_array($action, ['run', 'seed'])) {

            if ($action === 'run') {
                $this->call('migrate');
            } else {
                $this->call('seecms:seed');
            }

        } elseif ($action === 'backup') {

            $start = microtime(true);
            $backup = new Backup();
            $backup->setTables($tables);
            $backup->setReceiveEmail($mail);
            $result = $backup->run();
            $tables = $result->getData();
            if ($tables && is_array($tables)) {
                foreach ($tables as $item) {
                    $this->line(sprintf('== %s : backup complete', $item));
                }
            }
            $end = microtime(true);
            $this->line('');
            $this->line('<comment>All Done. Took ' . sprintf('%.4fs', $end - $start) . '</comment>');

        } else {
            $this->line($this->help);
        }

    }
}
